-- UISkyActivityRankingList
-- Create by chendh
-- 天空排行榜界面

-- UISkyActivityRankingList 继承自layer
UISkyActivityRankingList = class("UISkyActivityRankingList", function()
    return cc.Layer:create();
end);

function UISkyActivityRankingList.create(activityId)
    return UISkyActivityRankingList.new(activityId);
end

-- 构造函数
function UISkyActivityRankingList:ctor(activityId)
    self:setName("UISkyActivityRankingList");

    local node = cc.CSLoader:createNode("layout/dungeon/RankingList.csb");
    self:addChild(node);
    self.node = node;
    self.activityId = activityId;
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册点击按钮事件
    self:registerTouchEvent();

    -- 注册事件回调函数
    self:registerEventCallback();

    -- 排行榜飞入效果标示
    self.flyFlag = true;

    -- 初始化排行榜
    self:init(true);

    -- 重绘
    self:redraw();

    self:resize();
end

function UISkyActivityRankingList:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UISkyActivityRankingList:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityRankingList");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 修改国籍
    local btnChange = findChildByName(self.node, "BT/btn_change_nation");
    btnChange:setVisible(false);

    -- 注册排行榜图标点击事件
    local sdkLeaderoardImg = findChildByName(self.node, "BT/sdk_leaderboad");
    sdkLeaderoardImg:setVisible(false);
end

-- 重绘界面
function UISkyActivityRankingList:redraw()
    -- 重绘排行榜标题
    local node = self.node;
    local titleLabel = findChildByName(self.node, "CT/title_bg/title");
    titleLabel:setString(getLocStr("sky_activity_top_title"));
    TextStyleM.setArtWordTitleStyle(titleLabel);
end

-- 初始化排行榜
function UISkyActivityRankingList:init(showEffect)
    local clearTimeLabel = findChildByName(self.node, "CT/clear_time");

    -- 绘制排行榜
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/dungeon/RankingListItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 获取子区域列表
    local topList = self:getTopList();

    if #topList < 1 then
        clearTimeLabel:setVisible(false);
        return;
    end
    clearTimeLabel:setString("");
    clearTimeLabel:setVisible(true);

    -- 左边距
    local leftMargin = 30;

    -- 行间距
    local gap = 4;
    local widgetHeight = 109;

    local totalNum = #topList;
    self.totalNum = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    startHeight = totalHeight;
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, math.max(totalHeight, scrollview:getInnerContainerSize().height)));

    self.items = {};
    local i = 1;
    for _, info in pairs(topList) do
        local child = widget:clone();
        local x = leftMargin;

        local y = startHeight - i * (widgetHeight + gap);

        child:setPositionX(x);
        child:setPositionY(y);

        table.insert(self.items, child);

        -- 初始化奖励
        child:setTag(i);
        self:initItem(child, info);

        scrollview:addChild(child);
        i = i + 1;
    end

    if showEffect and self.flyFlag then
        local list = {};
        for j =1, #self.items, 1 do
            table.insert(list, self.items[j]);
        end
        commonScrollItemFlyIn(list);
        self.flyFlag = false;
    end

    -- 时间描述
    local function remainTimeToString(iTime)
        local remainingStr = "";
        if iTime >= 86400 then
            -- "xx天"
            remainingStr = string.format(getLocStr("reset_days"), math.floor(iTime / 86400));
        elseif iTime >= 3600 then
            -- "xx小时"
            remainingStr = string.format(getLocStr("reset_hour"), math.floor(iTime / 3600));
        elseif iTime >= 60 then
            -- "xx分钟"
            remainingStr = string.format(getLocStr("reset_minute"), math.floor(iTime / 60));
        else
            -- "xx秒"
            remainingStr = string.format(getLocStr("reset_second"), iTime);
        end

        return remainingStr;
    end

    -- 绘制重置时间
    local function tick()
        local clearTimeLabel = findChildByName(self.node, "CT/clear_time");
        local remainingTime = TopM.getActivityRemainingTime(self.activityId);

        if remainingTime < 0 then
            clearTimeLabel:setString("");
            clearTimeLabel:setVisible(false);
        else
            local remainingStr = remainTimeToString(remainingTime);
            TextStyleM.setTextStyle(clearTimeLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_YELLOW, true, -3);
            clearTimeLabel:setString(string.format(getLocStr("ranking_list_reset_time"), remainingStr));

            performWithDelay(self, tick, 1);
        end
    end

    tick();
end

-- 初始化排行榜的项目
function UISkyActivityRankingList:initItem(node, info)
    -- 积分
    local integrationLabel = findChildByName(node, "integration_label");
    TextStyleM.setTextStyle(integrationLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
    TextStyleM.setOutlineStyle(integrationLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    integrationLabel:setString(getLocStr("dungeon_score"));

    -- 积分数
    local integrationNum = findChildByName(node, "integration_num");
    TextStyleM.setTextStyle(integrationNum, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
    TextStyleM.setOutlineStyle(integrationNum, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    integrationNum:setString(tostring(info["score"]));

    -- 名字
    local nameLabel = findChildByName(node, "name_label");
    nameLabel:setString(getNickName(tostring(info["name"])));
    nameLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    nameLabel:setTextColor(TextStyleM.TEXT_COLOR_CREAM);

    -- 排名
    local rank = info["rank"];
    --local tag = node:getTag();

    local placeImg = findChildByName(node, "place_icon");
    placeImg:setVisible(false);
    if rank ~= nil then
        if rank < 4 and rank > 0 then
            placeImg:setVisible(true);
            local iconPath   = getTopListIcon("place" .. rank);
            placeImg:loadTexture(iconPath);
        end
    else
        rank = FormulaM.invoke("CALC_SKY_ACTIVITY_RANK", self.activityId, info["score"]);
    end
    -- 第几名
    local layerLabel = findChildByName(node, "layer_label");
    TextStyleM.setTextStyle(layerLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_ORANGE, true, -2);
    TextStyleM.setOutlineStyle(layerLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    layerLabel:setString(string.format(getLocStr("sky_activity_rank"), tostring(rank)));

    -- 国籍
    local nation = findChildByName(node, "bg/nationality");
    local nationId = info["nation_id"] or TopM.getDefaultNationId();
    local icon = TopM.queryNationality(nationId, "icon");
    local nationImgPath = getNationalityIconPath(icon);
    nation:loadTexture(nationImgPath);

    -- 出战的冈布奥
    local activePet = findChildByName(node, "hero_icon");
    local petId = info["activity_pet"];

    local icon = NewAirShipM.query(petId, "icon");
    local iconPath = getAirShipImgPath(icon);
    activePet:loadTexture(iconPath);
    activePet:setScale(0.4);

    -- 副炮不显示
    local imgLictorPet1 = findChildByName(node, "lictor_icon1");
    local imgLictorPet2 = findChildByName(node, "lictor_icon2");
    imgLictorPet1:setVisible(false);
    imgLictorPet2:setVisible(false);
end

function UISkyActivityRankingList:getTopList()
    -- 获取排行榜信息
    local list = TopM.getActivityTopData(self.activityId);
    local result = {};
    for _, info in ipairs(list) do
        if info["rank"] then
            local rank = tonumber(info["rank"]);
            if rank <= 10 or info["rid"] == ME.user.dbase:query("rid") then
                table.insert(result, info);
            end
        else
            if info["rid"] == ME.user.dbase:query("rid") then
                table.insert(result, info);
            end
        end
    end
    return result;
end

-- 注册函数回调
function UISkyActivityRankingList:registerEventCallback()
    -- 关注排行榜list
    EventMgr.register("UISkyActivityRankingList", event.ACTIVITY_TOP_DATA_UPDATED, function()
        -- 刷新排行榜
        self:init(true);
    end);

    -- 关注活动关闭事件
    EventMgr.register("UISkyActivityRankingList", event.ACTIVITY_CLOSE, function(args)
        -- 如果是当前活动关闭了，那么退出界面
        if self.activityId == args["id"] then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyActivityRankingList");
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISkyActivityRankingList 界面析构清理");
            EventMgr.removeAll("UISkyActivityRankingList");
        elseif ev == "enter" then

        end
    end);
end